package com.qf.mrboot2.service.impl;

import com.qf.mrboot2.entity.Order;
import com.qf.mrboot2.dao.OrderDao;
import com.qf.mrboot2.result.ResponseCode;
import com.qf.mrboot2.result.ResponseData;
import com.qf.mrboot2.service.OrderService;
import com.qf.mrboot2.util.SmsUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * (Order)表服务实现类
 *
 * @author makejava
 * @since 2021-06-02 15:59:49
 */
@Service("orderService")
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderDao orderDao;

    /**
     * 通过ID查询单条数据
     *
     * @param oId 主键
     * @return 实例对象
     */
    @Override
    public Order queryById(Integer oId) {
        return this.orderDao.queryById(oId);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<Order> queryAllByLimit(int offset, int limit) {
        return this.orderDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param order 实例对象
     * @return 实例对象
     */
    @Transactional
    @Override
    public ResponseData insert(Order order) {
        try {
            //发送短信
            String code = SmsUtil.SendMsg(order.getTel());
            if(code == null){
                return new ResponseData("000201","短信发送失败",null);
            }
            //添加数据
            order.setCode(code);
            order.setSubtime(new Date());
            order.setStatus(0);
            int i = orderDao.insert(order);
            if(i>0){
                return new ResponseData(ResponseCode.SUCCESS,null);
            }else{
                return new ResponseData(ResponseCode.FAILED,null);
            }
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResponseData(ResponseCode.FAILED,null);
        }


    }

    /**
     * 修改数据
     *
     * @param order 实例对象
     * @return 实例对象
     */
    @Override
    public Order update(Order order) {
        this.orderDao.update(order);
        return this.queryById(order.getoId());
    }

    /**
     * 通过主键删除数据
     *
     * @param oId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer oId) {
        return this.orderDao.deleteById(oId) > 0;
    }
}
